using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Volo.Abp.AspNetCore.Mvc;
using Matrix.Bff.Application.Aggregators;

namespace Matrix.Bff.HttpApi.Controllers
{
    /// <summary>
    /// 用户档案控制器
    /// 提供BFF层的用户信息聚合接口
    /// </summary>
    [ApiController]
    [Route("api/bff/user-profile")]
    public class UserProfileController : AbpControllerBase
    {
        private readonly UserAggregator _userAggregator;
        private readonly ILogger<UserProfileController> _logger;

        public UserProfileController(
            UserAggregator userAggregator,
            ILogger<UserProfileController> logger)
        {
            _userAggregator = userAggregator;
            _logger = logger;
        }

        /// <summary>
        /// 获取用户完整档案信息
        /// </summary>
        [HttpGet("{userId}")]
        public async Task<UserProfileDto> GetUserProfileAsync(Guid userId)
        {
            _logger.LogInformation("获取用户档案请求: {UserId}", userId);

            try
            {
                var profile = await _userAggregator.GetUserProfileAsync(userId);
                return profile;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户档案失败: {UserId}", userId);
                throw;
            }
        }

        /// <summary>
        /// 批量获取用户档案信息
        /// </summary>
        [HttpPost("batch")]
        public async Task<List<UserProfileDto>> GetUserProfilesAsync([FromBody] BatchUserProfileRequest request)
        {
            _logger.LogInformation("批量获取用户档案请求，用户数量: {UserCount}", request.UserIds?.Count ?? 0);

            try
            {
                var profiles = await _userAggregator.GetUserProfilesAsync(request.UserIds ?? new List<Guid>());
                return profiles;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量获取用户档案失败");
                throw;
            }
        }

        /// <summary>
        /// 验证用户权限完整性
        /// </summary>
        [HttpGet("{userId}/permission-integrity")]
        public async Task<PermissionIntegrityCheckDto> CheckUserPermissionIntegrityAsync(Guid userId)
        {
            _logger.LogInformation("检查用户权限完整性请求: {UserId}", userId);

            try
            {
                var checkResult = await _userAggregator.CheckUserPermissionIntegrityAsync(userId);
                return checkResult;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "检查用户权限完整性失败: {UserId}", userId);
                throw;
            }
        }

        /// <summary>
        /// 清除用户档案缓存
        /// </summary>
        [HttpDelete("{userId}/cache")]
        public async Task ClearUserProfileCacheAsync(Guid userId)
        {
            _logger.LogInformation("清除用户档案缓存请求: {UserId}", userId);

            try
            {
                await _userAggregator.ClearUserProfileCacheAsync(userId);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清除用户档案缓存失败: {UserId}", userId);
                throw;
            }
        }

        /// <summary>
        /// 获取当前用户档案信息
        /// </summary>
        [HttpGet("current")]
        public async Task<UserProfileDto> GetCurrentUserProfileAsync()
        {
            var userId = CurrentUser.Id;
            if (userId == Guid.Empty)
            {
                throw new UnauthorizedAccessException("用户未登录");
            }

            _logger.LogInformation("获取当前用户档案请求: {UserId}", userId);

            try
            {
                var profile = await _userAggregator.GetUserProfileAsync(userId);
                return profile;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取当前用户档案失败: {UserId}", userId);
                throw;
            }
        }

        /// <summary>
        /// 刷新当前用户档案缓存
        /// </summary>
        [HttpPost("current/refresh")]
        public async Task<UserProfileDto> RefreshCurrentUserProfileAsync()
        {
            var userId = CurrentUser.Id;
            if (userId == Guid.Empty)
            {
                throw new UnauthorizedAccessException("用户未登录");
            }

            _logger.LogInformation("刷新当前用户档案请求: {UserId}", userId);

            try
            {
                // 先清除缓存
                await _userAggregator.ClearUserProfileCacheAsync(userId);

                // 重新获取档案
                var profile = await _userAggregator.GetUserProfileAsync(userId);
                return profile;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "刷新当前用户档案失败: {UserId}", userId);
                throw;
            }
        }
    }

    /// <summary>
    /// 批量用户档案请求
    /// </summary>
    public class BatchUserProfileRequest
    {
        /// <summary>
        /// 用户ID列表
        /// </summary>
        public List<Guid> UserIds { get; set; } = new();
    }
}